<?php

/**
 * 融云控制器相关接口，计划全部迁移到此
 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Model\Hint;
use App\Http\Model\RoomUser;
use App\Http\Services\UserServices;
use App\Http\Services\MsgServices;
use App\Http\Services\RoomServices;
use App\Http\Services\RoomUserServices;
use App\Http\Services\NewRoomMicroServices;

class RongCloudController extends Controller
{
    protected $request;

    // 定义常用响应
    private const SUCCESS_RESPONSE = ['code' => Hint::SUCCESS, 'msg' => 'success', 'data' => []];

    public function __construct( Request $request )
    {
        $this->request = $request;
    }

    /**
     * 融云回调 音视频房间状态同步
     * https://doc.rongcloud.cn/rtcserver/-/-/room/room-status-callback
     * 
     * @return void
     */
    public function rongcloudVoiceCallback( UserServices $userServices )
    {
        try {
            $callbackData = file_get_contents ( "php://input" );
            $callbackData = json_decode ( $callbackData, true );

            if ( ! empty ( $callbackData['userId'] ) && ! empty ( $callbackData['event'] ) ) {
                $userId = $callbackData['userId'];
                $event = $callbackData['event'];

                // 定义通话结束事件
                $endCallEvents = [3, 12, 15, 17, 18, 22];
                // 定义通话开始事件
                $startCallEvents = [2, 11, 23];

                if ( in_array ( $event, $endCallEvents ) ) {
                    $userServices->identityStatusUpdate ( $userId, 1, ['identity_status' => 3] );
                } elseif ( in_array ( $event, $startCallEvents ) ) {
                    $userServices->identityStatusUpdate ( $userId, 3, ['identity_status' => 1] );
                }
            }
        } catch ( \Exception $e ) {
            write_log ( 'rongcloud', "rongcloudVoiceCallback ERROR: " . $e->getMessage (), $callbackData ?? [] );
        }
    }

    /**
     * 审核结果回调
     *
     * 文档地址：https://doc.rongcloud.cn/imserver/server/v1/security/audit-result
     * 
     * @return \Illuminate\Http\JsonResponse
     */
    public function contentAuditCallback( MsgServices $msgServices )
    {
        $params = $this->request->all ();

        if ( ! isset ( $params['result'] ) ) {
            return response ()->json ( self::SUCCESS_RESPONSE );
        }

        // result=审核结果，10000 为正常;10001 为审核不通过
        if ( intval ( $params['result'] ) == 10000 ) {
            return response ()->json ( self::SUCCESS_RESPONSE );
        }

        $content = json_decode ( $params['content'], true );
        $fromUserId = intval ( $content['fromUserId'] );
        $targetId = intval ( $content['targetId'] );
        $conversationType = strtolower ( $content['conversationType'] );

        write_log ( 'rongcloud', 'contentAuditCallback', $content );

        if ( $conversationType == 'person' ) {
            $senderMessage = "你发送的内容含有敏感词汇，已经被屏蔽，对方无法查看";
            $receiverMessage = "对方发送的内容含敏感词汇，已屏蔽该条内容";

            $msgServices->sendPrivateChatViolation ( $targetId, $fromUserId, $senderMessage );
            $msgServices->sendPrivateChatViolation ( $fromUserId, $targetId, $receiverMessage );

        }

        return response ()->json ( self::SUCCESS_RESPONSE );
    }

    /**
     * 订阅用户在线状态
     * 文档地址 https://docs.rongcloud.cn/platform-chat-api/user/service-config#%E8%AE%A2%E9%98%85%E7%94%A8%E6%88%B7%E5%9C%A8%E7%BA%BF%E7%8A%B6%E6%80%81
     */
    public function updateUserOnlineStatus( RoomUser $roomUser, RoomServices $roomServices, RoomUserServices $roomUserServices, NewRoomMicroServices $newRoomMicroServices )
    {
        // 应该有一部分融云消息效验
        write_log ( 'rongcloud', 'updateUserOnlineStatus', $this->request->all () );

        // 验证请求是否为JSON
        $userStatuses = $this->request->all ();

        foreach ( $userStatuses as $value ) {
            //网页的不处理
            if ( ! empty ( $value['os'] ) && $value['os'] == 'Websocket' ) {
                continue;
            }
            // 只处理真实用户ID
            if ( ! is_numeric ( $value['userid'] ) ) {
                continue;
            }

            $userId = $value['userid'];

            // 用户状态变更事件。0 - 用户已上线。1 - 用户已离线。2：用户已登出。
            if ( $value['status'] == 0 ) {
                $roomServices->setRongCloudOnline ( $userId, $value['time'] );
            }
            
            // // 离开房间和脱麦处理
            // $roomId = $roomUserServices->getCurRoomId ( $userId );
            // $newRoomMicroServices->roomUserQuitForData ( $roomId, $userId );
  
            // 融云离线状态更新
            // $roomServices->setRongCloudOffline ( $userId, $value['time'] );
            // $roomUser->removeUserFromRongyun ( $userId );
        }

        return response ()->json ( self::SUCCESS_RESPONSE );
    }
}